package leetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

class Solution {


    public static void main(String[] args) {
        int[] arr = {1,1,1,2,2,2,2,3,3,3};
        int k = 2;
        int[] ints = topKFrequent(arr, k);
        System.out.println(ints);

    }


    public static int[] topKFrequent(int[] nums, int k) {
        //放入Map集合
        Map<Integer,Integer> map = new HashMap<>();
        for(int num : nums){
            map.put(num,map.getOrDefault(num,0) + 1);
        }
        //排序 创建打顶堆
        PriorityQueue<int[]> pq = new PriorityQueue<>((pair1, pair2) -> pair2[1] - pair1[1]);
        for(Map.Entry<Integer,Integer> entry : map.entrySet()){
            pq.add(new int[]{
                    entry.getKey(),
                    entry.getValue()
            });
        }
        //最后输出
        int[] ens = new int[k];
        for(int i = 0; i < k; i++){
            ens[i] = pq.poll()[0];
        }

        return ens;
    }
}
